package com.egao.common.manage.student;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.core.Constants;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Preach;
import com.egao.common.module.company.entity.PreachCloud;
import com.egao.common.module.company.entity.Recruit;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.pushInformation.PushInformationConstants;
import com.egao.common.module.pushInformation.entity.PushInformation;
import com.egao.common.module.pushInformation.entity.PushInformationPosition;
import com.egao.common.module.pushInformation.param.PushInformationParam;
import com.egao.common.module.pushInformation.service.PushInformationPositionService;
import com.egao.common.module.pushInformation.service.PushInformationService;
import com.egao.common.module.student.constants.StudentResumeConstants;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.system.constants.EmailConstants;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.EmailService;
import com.egao.common.module.system.service.UserService;
import com.egao.common.publicly.service.PubliclyPreachCloudService;
import com.egao.common.publicly.service.PubliclyPreachService;
import com.egao.common.publicly.service.PubliclyRecruitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lym
 * @date 2024/8/28 13:51
 */
@Api(tags = "学生推送信息")
@RestController
@RequestMapping("${api}")
public class StudentPushInformationController extends BaseController {

    @Resource
    private PushInformationService pushInformationService;
    @Resource
    private StudentService studentService;
    @Resource
    private PushInformationPositionService pushInformationPositionService;
    @Resource
    private PubliclyRecruitService publiclyRecruitService;
    @Resource
    private PubliclyPreachService publiclyPreachService;
    @Resource
    private PubliclyPreachCloudService publiclyPreachCloudService;
    @Resource
    private CompanyService companyService;
    @Resource
    private UserService userService;
    @Resource
    private EmailService emailService;

    @Value("${minio.resumeDir}")
    private String resumeDir;

    @Value("${minio.minioDir}")
    private String minioDir;

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "推送信息分页列表")
    @GetMapping("/student/push-information/page")
    public PageResult<PushInformation> page(HttpServletRequest request) {
        // 查询学生信息
        Student student = studentService.getByUserId(getLoginUserId());
        if (student == null) {
            PageResult<PushInformation> pageResult = new PageResult<>();
            pageResult.setCode(Constants.RESULT_ERROR_CODE);
            pageResult.setMsg("没有查询到学生信息");
            return pageResult;
        }

        // 查询推送信息
        PageParam<PushInformationParam> pageParam = new PageParam<>(request);
        pageParam.getPageData().put("studentId", student.getId());
        pageParam.getPageData().put("pushState", PushInformationConstants.PUSH_STATE_SUCCESS);
        List<PushInformation> list = pushInformationService.listPage(pageParam);

        // 查询推送信息职位匹配数据
        if (!CollectionUtil.isEmpty(list)) {
            List<Integer> pushInformationIdList = list.stream().map(PushInformation::getId).distinct().collect(Collectors.toList());
            List<PushInformationPosition> pushInformationPositionList = pushInformationPositionService.list(new LambdaQueryWrapper<PushInformationPosition>()
                    .in(PushInformationPosition::getPushInformationId, pushInformationIdList)
            );

            for (PushInformation pushInformation : list) {
                List<PushInformationPosition> positionList = pushInformationPositionList.stream().filter(d -> pushInformation.getId().equals(d.getPushInformationId())).collect(Collectors.toList());
                pushInformation.setPositionList(positionList);
            }
        }

        return new PageResult<>(list, pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "推荐信息详情")
    @GetMapping("/student/push-information/detail/{id}")
    public JsonResult detail(@PathVariable Integer id) {
        PushInformation pushInformation = pushInformationService.getById(id);
        if (pushInformation == null) {
            return JsonResult.miss();
        }

        Student student = studentService.getByUserId(getLoginUserId());
        if (student == null) {
            return JsonResult.miss();
        }

        // 登录学生ID和信息学生ID不一致返回404
        if (!student.getId().equals(pushInformation.getStudentId())) {
            return JsonResult.miss();
        }

        // 查询具体就业信息
        String companyContent = "";
        switch (pushInformation.getCategory()) {
            case PushInformationConstants.CATEGORY_RECRUIT:
                Recruit recruit = publiclyRecruitService.getId(pushInformation.getBusinessId());
                pushInformation.setRecruit(recruit);
                Company company = companyService.getById(recruit.getCompanyId());
                companyContent = company != null ? company.getContent() : "";
                break;
            case PushInformationConstants.CATEGORY_PREACH:
                Preach preach = publiclyPreachService.getId(pushInformation.getBusinessId());
                pushInformation.setPreach(preach);
                break;
            case PushInformationConstants.CATEGORY_PREACH_CLOUD:
                PreachCloud preachCloud = publiclyPreachCloudService.getId(pushInformation.getBusinessId());
                pushInformation.setPreachCloud(preachCloud);
                break;
            default:
                return JsonResult.miss();
        }

        // 消息都为空表示没有查询到消息
        if (pushInformation.getRecruit() == null &&
                pushInformation.getPreach() == null &&
                pushInformation.getPreachCloud() == null) {
            return JsonResult.miss();
        }

        // 查询推送匹配数据
        List<PushInformationPosition> positionList = pushInformationPositionService.list(new LambdaQueryWrapper<PushInformationPosition>()
                .eq(PushInformationPosition::getPushInformationId, pushInformation.getId())
        );
        pushInformation.setPositionList(positionList);

        // 更新查看状态和时间
        if (PushInformationConstants.READ_STATE_WAIT == pushInformation.getReadState()) {
            pushInformation.setReadState(PushInformationConstants.READ_STATE_READ);
            pushInformation.setReadTime(new Date());
            pushInformationService.updateById(pushInformation);
        }

        return JsonResult.ok().setData(pushInformation).put("companyContent", companyContent);
    }

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "发送简历")
    @GetMapping("/student/push-information/resume/{id}")
    public JsonResult resume(@PathVariable Integer id) throws MessagingException {
        PushInformation pushInformation = pushInformationService.getById(id);
        if (pushInformation == null) {
            return JsonResult.error("未查询到推送信息");
        }

        Student student = studentService.getByUserId(getLoginUserId());
        if (student == null) {
            return JsonResult.error("未查询到学生信息");
        }

        String resumeUrl = student.getResumeUrl();
        if (StrUtil.isBlank(resumeUrl)) {
            return JsonResult.error("未找到简历。请先在就业意向填报中提交“标准版简历”或“自定义上传简历”");
        }

        // resumeDir H:\website\minio\resume
        // minioDir H:\website\minio

        // resumeDir D:\components\minio\resume
        // minioDir D:\components\minio
        if (StudentResumeConstants.RESUME_TYPE.equals(student.getResumeType())) {
            // 自定义简历
            resumeUrl = resumeDir + "\\resume\\" + student.getId() + "\\resume.pdf";
        } else {
            // 标准简历
            String[] strings = resumeUrl.split("9000");
            resumeUrl = minioDir + strings[1];
            resumeUrl = resumeUrl.replaceAll("/", "\\\\");
        }

        File file = FileUtil.file(resumeUrl);
        long fileLength = file.length();
        if (0L == fileLength) {
            return JsonResult.error("未找到简历。请先在就业意向填报中提交“标准版简历”或“自定义上传简历”");
        }

        // 查询单位邮箱
        Company company = companyService.getById(pushInformation.getCompanyId());
        if(company == null){
            return JsonResult.error("未查询到单位信息");
        }
        User user = userService.getById(company.getUserId());
        if (user == null) {
            return JsonResult.error("未查询到单位用户信息");
        }
        String companyEmail = user.getUsername();

        // 发送邮件
        emailService.sendFileEmail(EmailConstants.TITLE_RESUME,
                company.getName(),
                student.getXm(),
                pushInformation.getTitle(),
                file,
                companyEmail);

        // 更新查看状态和时间
        PushInformation update = new PushInformation();
        update.setId(pushInformation.getId());
        update.setResumeState(PushInformationConstants.RESUME_STATE_SEND);
        update.setResumeTime(new Date());
        pushInformationService.updateById(update);

        return JsonResult.ok();
    }

}
